﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace musicapi.Utils
{
    public class LogHelper
    {

        #region 自定义成员变量
        private static int m_maxfilesize = 100;
        private static int m_maxfilecount = 100;
        private FileInfo m_fileinfo;
        private static ReaderWriterLock writelock = new ReaderWriterLock();

        #endregion

        public LogHelper()
        {
            string path = string.Format(AppDomain.CurrentDomain.BaseDirectory + "Log\\{0}.txt", DateTime.Now.ToString("yyyyMMdd"));
            try
            {
                m_fileinfo = new FileInfo(path);
                if (m_fileinfo.Exists)
                {
                    if (CanBackup())
                    {
                        this.Backup();
                        this.CreatLog();
                    }
                }
                else
                {
                    this.CreatLog();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("初始化日志文件发生错误" + ex.ToString());
            }
        }
        /// <summary>
        /// 是否可以备份
        /// </summary>
        /// <returns></returns>
        private bool CanBackup()
        {
            try
            {
                writelock.AcquireReaderLock(-1);
                if (m_fileinfo.Length / ((long)0x400) > m_maxfilesize)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("判断是否需要备份日志文件时，发生错误" + ex.ToString());
            }
            finally
            {
                writelock.ReleaseReaderLock();
            }
        }
        /// <summary>
        /// 备份日志文件
        /// </summary>
        private void Backup()
        {
            int filecount = 0;
            string bakfilename = "";
            try
            {
                writelock.AcquireWriterLock(-1);
                FileInfo[] files = m_fileinfo.Directory.GetFiles(m_fileinfo.Name + ".*");
                filecount = files.Length;
                bakfilename = m_fileinfo.Name.Split('.')[0] + "_" + filecount.ToString() + ".txt";
                if (filecount > m_maxfilecount)
                {
                    files[1].Delete();
                }
                this.m_fileinfo.CopyTo(m_fileinfo.Directory + "//" + bakfilename, true);
                this.CreatLog();
            }
            catch (Exception ex)
            {
                throw new Exception("备份日志文件发生错误" + ex.ToString());
            }
            finally
            {
                writelock.ReleaseWriterLock();
            }
        }


        /// <summary>
        /// 创建日志文件
        /// </summary>
        private void CreatLog()
        {
            TextWriter logwrite = null;
            try
            {
                writelock.AcquireWriterLock(-1);
                if (!this.m_fileinfo.Directory.Exists)
                {
                    this.m_fileinfo.Directory.Create();
                }
                logwrite = this.m_fileinfo.CreateText();
                logwrite.WriteLine("#------------------------------------------------------");
                logwrite.WriteLine("#     系统日志                                         ");
                logwrite.WriteLine("#						                               ");
                logwrite.WriteLine("#     Create  at " + DateTime.Now.ToString() + "   ");
                logwrite.WriteLine("#                                                      ");
                logwrite.WriteLine("#------------------------------------------------------");
                logwrite.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("创建系统日志文件出错!" + ex.ToString());
            }
            finally
            {
                writelock.ReleaseWriterLock();
                if (logwrite != null)
                {
                    logwrite.Close();
                }
            }
        }


        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="content"></param>
        public void WriteLog(string content)
        {
            TextWriter logwrite = null;
            try
            {
                writelock.AcquireWriterLock(-1);
                logwrite = m_fileinfo.AppendText();
                logwrite.Write("\r\n" + DateTime.Now.ToString() + ":" + content + "\r\n");
                logwrite.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("记录日志发生错误" + ex.Message);
            }
            finally
            {
                if (logwrite != null)
                {
                    logwrite.Close();
                }
                writelock.ReleaseWriterLock();
            }
        }
    }
}
